package main

import (
	"context"
	"crypto/md5"
	"fmt"
	maps "gateway/kitex_gen/maps"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

// LocationServiceImpl implements the last service interface defined in the IDL.
type LocationServiceImpl struct{}

// Map implements the LocationServiceImpl interface.
func (s *LocationServiceImpl) Map(ctx context.Context, req *maps.MapReq) (resp *maps.MapResp, err error) {
	// TODO: Your code here...
	return
}

// Location implements the LocationServiceImpl interface.
func (s *LocationServiceImpl) Location(ctx context.Context, req *maps.LocationReq) (resp *maps.LocationResp, err error) {
	// TODO: Your code here...
	ak := "saBIRObX0TnlCePE7zS8F9LZ0QzNz7mh"

	// 此处填写您在控制台-应用管理-创建应用时，校验方式选择sn校验后生成的SK
	sk := "b6jlzwrS3SQN3i17umVBhTzfrQ67wuEv"

	// 服务地址
	host := "https://api.map.baidu.com"

	// 接口地址
	uri := "/reverse_geocoding/v3/"

	// 设置请求参数
	params := [][]string{
		{"ak", ak},
		{"output", "json"},
		{"coordtype", "bd09ll"},
		{"extensions_poi", "1"},
		{"location", fmt.Sprintf("%s,%s", req.Lat, req.Lng)},
	}

	paramsArr := make([]string, 0)
	for _, v := range params {
		kv := v[0] + "=" + (v[1])
		paramsArr = append(paramsArr, kv)
	}
	paramsStr := strings.Join(paramsArr, "&")

	// 计算sn
	queryStr := url.QueryEscape(uri + "?" + paramsStr)
	sn := calculateSN(queryStr, sk)

	// 发起请求
	request, err := url.Parse(host + uri + "?" + paramsStr + "&sn=" + sn)
	if nil != err {
		fmt.Printf("host error: %v", err)
		return
	}

	resps, err1 := http.Get(request.String())
	// 请注意，此处打印的url为非urlencode后的请求串
	// 如果将该请求串直接粘贴到浏览器中发起请求，由于浏览器会自动进行urlencode，会导致返回sn校验失败
	fmt.Printf("url: %s\n", request.String())
	defer resps.Body.Close()
	if err1 != nil {
		fmt.Printf("request error: %v", err1)
		return
	}
	body, err2 := ioutil.ReadAll(resps.Body)
	if err2 != nil {
		fmt.Printf("response error: %v", err2)
	}

	fmt.Println(string(body))

	return &maps.LocationResp{
		MessageLocation: string(body),
	}, nil
}
func calculateSN(queryStr string, sk string) string {
	str := queryStr + sk
	key := md5.Sum([]byte(str))
	sn := fmt.Sprintf("%x", key)
	return sn
}
